const { ethers } = require("hardhat");

async function main() {
    const [deployer] = await ethers.getSigners();
    console.log(`📝 诊断账户: ${deployer.address}`);

    const PROXY_ADDRESS = "0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512";

    console.log(`🔍 检查代理合约: ${PROXY_ADDRESS}`);

    // 检查合约代码
    const code = await ethers.provider.getCode(PROXY_ADDRESS);
    console.log(`📦 合约代码长度: ${code.length}`);
    console.log(`🔎 是否有代码: ${code !== '0x'}`);

    if (code === '0x') {
        console.log("❌ 代理合约没有代码，可能未正确部署");
        return;
    }

    // 尝试直接读取存储槽（代理合约的 implementation 在 slot 0）
    console.log("\n🔍 直接读取存储槽...");
    try {
        const implementationSlot = await ethers.provider.getStorage(PROXY_ADDRESS, 0);
        console.log(`📋 Slot 0 (implementation): ${implementationSlot}`);

        const adminSlot = await ethers.provider.getStorage(PROXY_ADDRESS, 2);
        console.log(`📋 Slot 2 (admin): ${adminSlot}`);

        const numberSlot = await ethers.provider.getStorage(PROXY_ADDRESS, 1);
        console.log(`📋 Slot 1 (number): ${numberSlot}`);
    } catch (error) {
        console.log("❌ 读取存储槽失败:", error.message);
    }

    // 尝试使用不同的 ABI 连接
    console.log("\n🔍 尝试不同的连接方式...");

    // 方法1: 使用最小 ABI
    const minimalABI = [
        "function implementation() view returns (address)",
        "function admin() view returns (address)"
    ];

    try {
        const proxyMinimal = new ethers.Contract(PROXY_ADDRESS, minimalABI, deployer);
        const impl = await proxyMinimal.implementation();
        console.log(`✅ 使用最小ABI获取 implementation: ${impl}`);
    } catch (error) {
        console.log(`❌ 最小ABI方式失败: ${error.message}`);
    }

    // 方法2: 尝试调用逻辑合约的函数
    try {
        const logicV1ABI = [
            "function getNumber() view returns (uint256)",
            "function version() view returns (string)"
        ];
        const proxyAsLogic = new ethers.Contract(PROXY_ADDRESS, logicV1ABI, deployer);
        const number = await proxyAsLogic.getNumber();
        console.log(`✅ 通过代理调用 getNumber(): ${number}`);

        const version = await proxyAsLogic.version();
        console.log(`✅ 通过代理调用 version(): ${version}`);
    } catch (error) {
        console.log(`❌ 调用逻辑合约函数失败: ${error.message}`);
    }
}

main()
    .then(() => process.exit(0))
    .catch((error) => {
        console.error("诊断失败:", error);
        process.exit(1);
    });